#!/usr/bin/env python3
"""
简化的MCP Stdio服务器 - 专门用于解决连接超时问题
跳过所有数据库初始化，直接启动MCP协议处理
"""

import asyncio
import sys
import json
from pathlib import Path
from typing import Dict, Any, Optional

# 添加项目根目录到路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root / 'src'))

from src.config import load_config


class NoOpOrchestrator:
    """无操作编排器 - 用于快速启动MCP服务"""
    
    def __init__(self, config: Dict[str, Any]):
        self.config = config
        self.is_initialized = False
    
    async def initialize(self):
        """快速初始化，不连接任何数据库"""
        self.is_initialized = True
    
    async def shutdown(self):
        """关闭"""
        self.is_initialized = False
    
    async def process_message(self, session_id: str, message: str, message_type: str = 'user') -> Dict[str, Any]:
        """处理消息 - 返回简单响应"""
        return {
            'response': f'Echo: {message}',
            'type': 'text',
            'metadata': {
                'session_id': session_id,
                'message_type': message_type
            }
        }
    
    async def upload_knowledge(self, content: str, title: str, user_id: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> str:
        """上传知识 - 返回模拟ID"""
        return 'mock_knowledge_id'
    
    async def search_knowledge(self, query: str, user_id: Optional[str] = None, limit: int = 5) -> list:
        """搜索知识 - 返回空结果"""
        return []
    
    async def create_session(self, user_id: str, session_config: Optional[Dict[str, Any]] = None) -> str:
        """创建会话 - 返回模拟ID"""
        return 'mock_session_id'


class SimpleMCPServer:
    """简化的MCP服务器"""
    
    def __init__(self, orchestrator: NoOpOrchestrator, config: Dict[str, Any]):
        self.orchestrator = orchestrator
        self.config = config
        self.tools = {}
        self.resources = {}
    
    async def initialize(self):
        """初始化服务器"""
        await self.orchestrator.initialize()
        
        # 注册基本工具
        self.tools = {
            'echo': {
                'name': 'echo',
                'description': 'Echo back the input message',
                'inputSchema': {
                    'type': 'object',
                    'properties': {
                        'message': {
                            'type': 'string',
                            'description': 'Message to echo back'
                        }
                    },
                    'required': ['message']
                }
            },
            'knowledge_upload': {
                'name': 'knowledge_upload',
                'description': 'Upload knowledge content',
                'inputSchema': {
                    'type': 'object',
                    'properties': {
                        'content': {'type': 'string'},
                        'title': {'type': 'string'}
                    },
                    'required': ['content', 'title']
                }
            }
        }
    
    async def handle_message(self, message: Dict[str, Any]) -> Dict[str, Any]:
        """处理MCP消息"""
        method = message.get('method')
        params = message.get('params', {})
        msg_id = message.get('id')
        
        try:
            if method == 'initialize':
                return {
                    'jsonrpc': '2.0',
                    'id': msg_id,
                    'result': {
                        'protocolVersion': '2024-11-05',
                        'capabilities': {
                            'tools': {
                                'listChanged': True
                            },
                            'resources': {
                                'subscribe': True,
                                'listChanged': True
                            }
                        },
                        'serverInfo': {
                            'name': 'mcp2-simple',
                            'version': '1.0.0'
                        }
                    }
                }
            
            elif method == 'tools/list':
                return {
                    'jsonrpc': '2.0',
                    'id': msg_id,
                    'result': {
                        'tools': list(self.tools.values())
                    }
                }
            
            elif method == 'tools/call':
                tool_name = params.get('name')
                arguments = params.get('arguments', {})
                
                if tool_name == 'echo':
                    message_text = arguments.get('message', '')
                    return {
                        'jsonrpc': '2.0',
                        'id': msg_id,
                        'result': {
                            'content': [{
                                'type': 'text',
                                'text': f'Echo: {message_text}'
                            }]
                        }
                    }
                
                elif tool_name == 'knowledge_upload':
                    content = arguments.get('content', '')
                    title = arguments.get('title', '')
                    doc_id = await self.orchestrator.upload_knowledge(content, title)
                    return {
                        'jsonrpc': '2.0',
                        'id': msg_id,
                        'result': {
                            'content': [{
                                'type': 'text',
                                'text': f'Knowledge uploaded successfully. ID: {doc_id}'
                            }]
                        }
                    }
                
                else:
                    return {
                        'jsonrpc': '2.0',
                        'id': msg_id,
                        'error': {
                            'code': -32601,
                            'message': f'Unknown tool: {tool_name}'
                        }
                    }
            
            elif method == 'resources/list':
                return {
                    'jsonrpc': '2.0',
                    'id': msg_id,
                    'result': {
                        'resources': []
                    }
                }
            
            else:
                return {
                    'jsonrpc': '2.0',
                    'id': msg_id,
                    'error': {
                        'code': -32601,
                        'message': f'Method not found: {method}'
                    }
                }
        
        except Exception as e:
            return {
                'jsonrpc': '2.0',
                'id': msg_id,
                'error': {
                    'code': -32603,
                    'message': f'Internal error: {str(e)}'
                }
            }


async def run_stdio_server(mcp_server: SimpleMCPServer):
    """运行stdio服务器"""
    await mcp_server.initialize()
    
    # 读取stdin并处理消息
    while True:
        try:
            # 从stdin读取一行
            line = await asyncio.get_event_loop().run_in_executor(None, sys.stdin.readline)
            if not line:
                break
            
            line = line.strip()
            if not line:
                continue
            
            # 解析JSON消息
            try:
                message = json.loads(line)
            except json.JSONDecodeError as e:
                # 发送错误响应
                error_response = {
                    'jsonrpc': '2.0',
                    'id': None,
                    'error': {
                        'code': -32700,
                        'message': f'Parse error: {str(e)}'
                    }
                }
                print(json.dumps(error_response), flush=True)
                continue
            
            # 处理消息
            response = await mcp_server.handle_message(message)
            
            # 发送响应
            print(json.dumps(response), flush=True)
        
        except KeyboardInterrupt:
            break
        except Exception as e:
            # 发送内部错误响应
            error_response = {
                'jsonrpc': '2.0',
                'id': None,
                'error': {
                    'code': -32603,
                    'message': f'Internal error: {str(e)}'
                }
            }
            print(json.dumps(error_response), flush=True)


async def main():
    """主函数"""
    try:
        # 加载配置（如果失败则使用默认配置）
        try:
            config = load_config('config')
        except Exception:
            config = {
                'app': {'name': 'mcp2-simple'},
                'database': {'enabled': False}
            }
        
        # 创建简化的编排器和服务器
        orchestrator = NoOpOrchestrator(config)
        mcp_server = SimpleMCPServer(orchestrator, config)
        
        # 启动stdio服务器
        await run_stdio_server(mcp_server)
    
    except Exception as e:
        # 向stderr输出错误，避免污染stdout
        sys.stderr.write(f"启动失败: {e}\n")
        sys.exit(1)


if __name__ == "__main__":
    asyncio.run(main())